package com.lw.alarm.filter;

import java.util.Date;

import javax.annotation.Resource;

import org.apache.shiro.util.Assert;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.druid.util.StringUtils;
import com.lw.alarm.model.AlarmNoticeLog;
import com.lw.alarm.model.AlarmServer;
import com.lw.alarm.model.enums.NoticeResult;
import com.lw.alarm.model.enums.NoticeWay;
import com.lw.alarm.service.AlarmNoticeLogService;
import com.lw.alarm.util.AliyunMNSHelper;
import com.xiaoleilu.hutool.lang.Validator;

/**
 * 
 * @Description: 责任链中的短信处理
 * @author wei.liu
 * @date 2017年4月19日 下午2:41:19
 * @version V1.0
 */
public class SMSFilter implements Filter {

	private final static Logger logger = LoggerFactory.getLogger(SMSFilter.class);
	private AlarmNoticeLogService alarmNoticeLogService;

	public SMSFilter(AlarmNoticeLogService alarmNoticeLogService) {
		super();
		this.alarmNoticeLogService = alarmNoticeLogService;
	}

	@Override
	public void doFilter(AlarmServer request, Response response, FilterChain chain) {

		if (!StringUtils.isEmpty(request.getNoticePhones())) {
			String[] phones = request.getNoticePhones().split(",");

			int length = phones.length;
			String smsTemplateCode = null;
			AlarmNoticeLog record = new AlarmNoticeLog();
			for (int i = 0; i < length; i++) {
				Assert.isTrue(Validator.isMobile(phones[i]), "不是手机号码！");
				record.setServerId(request.getId());
				record.setServerName(request.getServerName());
				if (request.getStatus() == 0) {
					record.setNoticeType((byte) 1);
					smsTemplateCode = AliyunMNSHelper.SERVER_BACK_TO_NORMAL;
				} else {
					smsTemplateCode = AliyunMNSHelper.SERVER_EXCEPTION;
					record.setNoticeType((byte) 0);
				}
				record.setCreateTime(new Date());
				record.setNoticeAddress(phones[i]);
				record.setNoticeWay((byte) NoticeWay.PHONE.ordinal());
				record.setNoticeResult((byte) NoticeResult.SUCCESS.ordinal());
				try {
					AliyunMNSHelper.sendMNS(request.getServerName(), phones[i], smsTemplateCode);
				} catch (Exception e) {
					record.setNoticeResult((byte) NoticeResult.SUCCESS.ordinal());
					logger.error("发短信件失败！", e);
				}
				logger.debug("========>开始记录发送短信日志");
				alarmNoticeLogService.insert(record);
			}
		}
		chain.doFilter(request, response, chain);
		response.responseStr.concat("---EmailFilter()");

	}
}
